package com.app.hmst.main;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.hmst.model.CategoryVO;
import com.app.hmst.model.HomestayInfoVO;
import com.app.hmst.model.HomestayVO;
import com.app.hmst.model.HouseInfoVO;
import com.app.hmst.model.IndicatorResultVO;
import com.app.hmst.model.IndicatorVO;
import com.app.hmst.model.SubCategoryVO;
import com.app.hmst.utils.GlobalVariable;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.roscopeco.ormdroid.Entity;

@SuppressLint({ "NewApi", "ValidFragment" }) public class AfterSaveEvaluateFormFragment extends Fragment{
	private View v;
	private SlidingMenu _sm;
	private ImageView menu_icon,confirmTOsave;
	private ListView lvAfterForm;
	private HomestayVO homestayVO;
	private HomestayInfoVO homestayInfoVO;
	private int checkDisable;
	private boolean isHomeStay;
	private HouseInfoVO houseInfoVO;
	public AfterSaveEvaluateFormFragment(SlidingMenu sm, HomestayVO homestayVO, HomestayInfoVO homestayInfoVO,HouseInfoVO houseInfoVO, boolean isHomeStay){
		this._sm = sm;
		this.homestayVO = homestayVO;
		this.homestayInfoVO = homestayInfoVO;
		this.isHomeStay = isHomeStay;
		this.houseInfoVO = houseInfoVO;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		System.gc();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		v = inflater.inflate(R.layout.after_save_page,container, false);
		confirmTOsave = (ImageView) v.findViewById(R.id.button1);

		lvAfterForm = (ListView) v.findViewById(R.id.lvForCon);
		lvAfterForm.setDivider(null);
        new InitAndLoadData().execute();

        
		menu_icon = (ImageView) v.findViewById(R.id.imageView6);
		menu_icon.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				_sm.toggle();
			}
		});
		return v;
	}
	private void switchFragment(Fragment fragment) {
		if (getActivity() == null)
			return;

		if (getActivity() instanceof HomeStayMainActivity) {
			HomeStayMainActivity fca = (HomeStayMainActivity) getActivity();
			fca.switchContent(fragment);
		}
	}
	public class CheckFormAdapter extends BaseAdapter{
		public List<TempShowList> _list;
		public ViewHolder viewHolder;
		public CheckFormAdapter(List<TempShowList> list){
			this._list = list;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return _list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return _list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			TempShowList temp;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.each_check_form_evaluate_list,null);
				viewHolder.editBtn = (ImageView) convertView.findViewById(R.id.imageView2);
				viewHolder.iconCheck = (ImageView) convertView.findViewById(R.id.imageView3);
				viewHolder.typeName = (TextView) convertView.findViewById(R.id.homeAddress1);
				viewHolder.detail = (TextView) convertView.findViewById(R.id.textView1);
				viewHolder.contain = (RelativeLayout) convertView.findViewById(R.id.each_second_menu_list);
			}else{
				convertView.setTag(viewHolder);
			}
			temp = _list.get(position);
			if (temp.isSuccess) {
				viewHolder.contain.setBackgroundColor(Color.parseColor("#ffffff"));
				viewHolder.editBtn.setImageDrawable(getResources().getDrawable(R.drawable.edit_btn_default));
				viewHolder.iconCheck.setImageDrawable(getResources().getDrawable(R.drawable.correct_check));
				viewHolder.typeName.setText(temp.getTypeName());
				viewHolder.detail.setText(temp.getResultNoSuccess());
			}else{
				viewHolder.contain.setBackgroundColor(Color.parseColor("#feff02"));
				viewHolder.editBtn.setImageDrawable(getResources().getDrawable(R.drawable.edit_btn_red));
				viewHolder.iconCheck.setImageDrawable(getResources().getDrawable(R.drawable.x_check_red));
				viewHolder.typeName.setText(temp.getTypeName());
				viewHolder.detail.setText(temp.getResultNoSuccess());
			}
			viewHolder.editBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//confirmTOsave.setImageDrawable(getResources().getDrawable(R.drawable.confirm_to_save_save));
					if(isHomeStay){
					switchFragment(new EvaluateFormFragment(_sm, homestayInfoVO,true,position));
					}else{
					switchFragment(new EvaluateFormFragment(_sm, homestayInfoVO,houseInfoVO,false,position));	
					}
				}
			});

			return convertView;			
		}
		
	}
	public class ViewHolder{
		private ImageView editBtn,iconCheck;
		private TextView typeName, detail;
		private RelativeLayout contain;
	}
	public class InitAndLoadData extends AsyncTask<String, Void, List<TempShowList>> implements OnCancelListener{
		ProgressHUD mProgressHUD;
		
    	@Override
    	protected void onPreExecute() {
        	mProgressHUD = ProgressHUD.show(getActivity(),"Loading Content...", true,true,this);
    		super.onPreExecute();
    	}
		@Override
		protected List<TempShowList> doInBackground(String... params) {
			// TODO Auto-generated method stub		
				TempShowList temp1;
				List<TempShowList> list = new ArrayList<TempShowList>();
				List<CategoryVO> categories = homestayVO.categories();
				for(CategoryVO cat : categories){
				temp1 = new TempShowList();
				int count = checkResult(cat);
				temp1.setSuccess(count==0);
				temp1.setTypeName(cat.no+"."+cat.title);
				temp1.setResultNoSuccess(count==0?"":getActivity().getString(R.string.result_text1)+count+getActivity().getString(R.string.result_text12));
				list.add(temp1);
					if(count!=0){
						checkDisable++;
					}
				}
			
			return list;
		}
		
		@Override
		protected void onPostExecute(List<TempShowList> result) {
			super.onPostExecute(result);
			if (result != null) {
				CheckFormAdapter adapter = new CheckFormAdapter(result);
				lvAfterForm.setAdapter(adapter);
				mProgressHUD.dismiss();
				
				if(checkDisable!=0){
					confirmTOsave.setImageDrawable(getResources().getDrawable(R.drawable.confirm_to_save_notsave));
				}else{
					confirmTOsave.setImageDrawable(getResources().getDrawable(R.drawable.confirm_to_save_save));
					confirmTOsave.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							boolean isSuccess = false;
							if(isHomeStay){
								List<IndicatorResultVO> indResultVOs = Entity
										.query(IndicatorResultVO.class)
										.where("homeId")
										.eq(homestayInfoVO.id)
										.and("houseId")
										.eq("0")
										.and("indicatorId")
										.in("select indicatorId From comapphmstmodelIndicatorResultVO ")
										.executeMulti();
				
								HomestayVO vo = new HomestayVO();
								HomestayVO homestayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOMESTAY).execute();
								
								if (indResultVOs == null
										|| indResultVOs.size() != vo.getFormSize(homestayVO)) {
									isSuccess = false;
								} else {
									isSuccess = true;
								}
							}else{
								List<IndicatorResultVO> indResultVOs = Entity
										.query(IndicatorResultVO.class)
										.where("homeId")
										.eq(homestayInfoVO.id)
										.and("houseId")
										.eq(houseInfoVO.id)
										.and("indicatorId")
										.in("select indicatorId From comapphmstmodelIndicatorResultVO ")
										.executeMulti();
				
								HomestayVO vo = new HomestayVO();
								HomestayVO homestayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOUSE).execute();
								
								if (indResultVOs == null || indResultVOs.size() != vo.getFormSize(homestayVO)) {
									isSuccess = false;
								} else {
									isSuccess = true;
								}
							}
							if(isSuccess){
								if(isHomeStay){
								homestayInfoVO.status ="C";
								homestayInfoVO.save();
								}else{
								houseInfoVO.status = "C";
								houseInfoVO.save();
								}
								getFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuFragment(_sm,true,homestayInfoVO)).commit();
							}
							
//							switchFragment(new GeneralInfoFragment(_sm,homestayInfoVO,true));
							switchFragment(new ViewAllSummaryEvaluatePageFragment(_sm,homestayInfoVO));
						}
					});
				}		
			} else {
				mProgressHUD.dismiss();
			}
			
		}
		@Override
		public void onCancel(DialogInterface dialog) {
			// TODO Auto-generated method stub
			mProgressHUD.dismiss();
		}
	}
	public int checkResult(CategoryVO cat){
		int failCount = 0;
		
		List<SubCategoryVO> subList = cat.subCategories();
		
		if(subList!=null && subList.size()>0){
			for(SubCategoryVO sub : subList){
				List<IndicatorVO> inList =  sub.indicators();
				if(inList!=null && inList.size()>0){
					for(IndicatorVO ind : inList){
						if(isHomeStay){
							List<IndicatorResultVO> list = Entity.query(IndicatorResultVO.class).where("indicatorId").eq(ind.id).and("homeId").eq(homestayInfoVO.id).executeMulti();
							if(list==null || list.isEmpty()){
								failCount++;
							}
						}else{
							List<IndicatorResultVO> list = Entity.query(IndicatorResultVO.class).where("indicatorId").eq(ind.id).and("homeId").eq(homestayInfoVO.id)
									.and("houseId").eq(houseInfoVO.id).executeMulti();
							if(list==null || list.isEmpty()){
								failCount++;
							}
						}
					}
				}
			}
		}
		return failCount;
	}
	public class TempShowList{
		public boolean isSuccess;
		public String typeName;
		public String resultNoSuccess;
		public boolean isSuccess() {
			return isSuccess;
		}
		public void setSuccess(boolean isSuccess) {
			this.isSuccess = isSuccess;
		}
		public String getTypeName() {
			return typeName;
		}
		public void setTypeName(String typeName) {
			this.typeName = typeName;
		}
		public String getResultNoSuccess() {
			return resultNoSuccess;
		}
		public void setResultNoSuccess(String resultNoSuccess) {
			this.resultNoSuccess = resultNoSuccess;
		}
		
	}
}
